<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档处理工具</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        h1 {
            color: #2c3e50;
            margin-bottom: 20px;
            text-align: center;
        }
        .upload-area {
            background-color: #fff;
            border: 2px dashed #3498db;
            border-radius: 5px;
            padding: 40px 20px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .upload-area:hover {
            border-color: #2980b9;
            background-color: #f8f9fa;
        }
        .btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            font-size: 16px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        .btn:hover {
            background-color: #2980b9;
        }
        .btn:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .process-btn {
            background-color: #2ecc71;
        }
        .process-btn:hover {
            background-color: #27ae60;
        }
        .download-btn {
            background-color: #e67e22;
        }
        .download-btn:hover {
            background-color: #d35400;
        }
        .loading {
            display: none;
            text-align: center;
            margin: 20px 0;
            font-style: italic;
            color: #7f8c8d;
        }
        .error {
            display: none;
            color: #e74c3c;
            text-align: center;
            margin: 20px 0;
            font-weight: bold;
        }
        .success {
            display: none;
            color: #2ecc71;
            text-align: center;
            margin: 20px 0;
            font-weight: bold;
        }
        .file-type-selector {
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
        }
        .file-type-selector label {
            margin: 0 10px;
            cursor: pointer;
        }
        .review-upload-section {
            margin-bottom: 10px;
        }
        .model-select {
            padding: 10px 20px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        /* 导航栏样式 */
        nav {
            background-color: #2980b9;
            padding: 10px 0;
            margin-bottom: 20px;
            border-radius: 5px;
        }
        nav ul {
            display: flex;
            justify-content: center;
            list-style: none;
        }
        nav ul li {
            margin: 0 15px;
        }
        nav ul li a {
            color: white;
            text-decoration: none;
            font-weight: bold;
            padding: 5px 10px;
            border-radius: 3px;
            transition: background-color 0.3s;
        }
        nav ul li a:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }
        nav ul li a.active {
            background-color: rgba(255, 255, 255, 0.3);
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>文档处理工具</h1>
        
        <!-- 导航菜单 -->
        <nav>
            <ul>
                <li><a href="/" class="active">文档处理</a></li>
                <li><a href="/model-playground.html">大模型验证中心</a></li>
            </ul>
        </nav>
        
        <div class="file-type-selector">
            <label>
                <input type="radio" name="fileType" value="word" checked> Word文档处理
            </label>
            <label>
                <input type="radio" name="fileType" value="excel"> Excel生成Prompt
            </label>
            <label>
                <input type="radio" name="fileType" value="review"> 文档审核检查
            </label>
        </div>
        
        <div id="uploadArea" class="upload-area">
            <p id="uploadText">拖拽文件到这里或点击选择文件</p>
            <input type="file" id="fileInput" accept=".docx,.xlsx" style="display: none">
            <button class="btn" onclick="document.getElementById('fileInput').click()">选择文件</button>
        </div>
        
        <!-- 文档审核检查的UI元素 -->
        <div id="reviewUploadArea" style="display: none; margin: 20px 0;">
            <div class="review-upload-section">
                <p>已上传Word文档: <span id="wordFileName">未选择</span></p>
                <input type="file" id="wordFileInput" accept=".docx" style="display: none">
                <button id="uploadWordBtn" class="btn" onclick="document.getElementById('wordFileInput').click()">上传Word文档</button>
            </div>
            <div class="review-upload-section" style="margin-top: 10px;">
                <p>已上传Excel文档: <span id="excelFileName">未选择</span></p>
                <input type="file" id="excelFileInput" accept=".xlsx" style="display: none">
                <button id="uploadExcelBtn" class="btn" onclick="document.getElementById('excelFileInput').click()">上传Excel文档</button>
            </div>
        </div>

        <!-- 模型选择器 -->
        <div id="modelSelector" style="display: none; margin: 20px 0;">
            <p>选择模型类型:</p>
            <select id="modelType" class="model-select">
                <option value="deepseek">大模型类型：Deepseek R1</option>
                <option value="qwen">大模型类型：Qwen2.5 32B</option>
            </select>
        </div>

        <div id="loading" class="loading">正在处理中...</div>
        <div id="error" class="error"></div>
        <div id="success" class="success"></div>
        <div class="actions">
            <button id="process-excel-btn" class="btn process-btn">生成Prompt</button>
            <button id="process-review-btn" class="btn process-btn" style="display: none;">开始审核检查</button>
            <button id="download-word-btn" class="btn download-btn">下载Markdown文件</button>
            <button id="download-excel-btn" class="btn download-btn">下载Excel文件</button>
        </div>
        <div id="preview"></div>
    </div>

    <script>
        const uploadArea = document.getElementById('uploadArea');
        const uploadText = document.getElementById('uploadText');
        const fileInput = document.getElementById('fileInput');
        const loading = document.getElementById('loading');
        const error = document.getElementById('error');
        const success = document.getElementById('success');
        const preview = document.getElementById('preview');
        const downloadWordBtn = document.getElementById('download-word-btn');
        const downloadExcelBtn = document.getElementById('download-excel-btn');
        const processExcelBtn = document.getElementById('process-excel-btn');
        const processReviewBtn = document.getElementById('process-review-btn');
        const fileTypeRadios = document.getElementsByName('fileType');
        const reviewUploadArea = document.getElementById('reviewUploadArea');
        const uploadWordBtn = document.getElementById('uploadWordBtn');
        const uploadExcelBtn = document.getElementById('uploadExcelBtn');
        const modelSelector = document.getElementById('modelSelector');
        const modelTypeSelect = document.getElementById('modelType');
        
        let downloadUrl = '';
        let currentFileType = 'word';
        let currentFileName = '';
        let tempFilePath = '';
        let uploadedFiles = {
            word: null,
            excel: null
        };

        // 切换文件类型处理模式
        fileTypeRadios.forEach(radio => {
            radio.addEventListener('change', (e) => {
                currentFileType = e.target.value;
                resetUI();
                updateAcceptedFileTypes();
            });
        });

        function updateAcceptedFileTypes() {
            if (currentFileType === 'word') {
                fileInput.accept = '.docx';
                uploadText.textContent = '拖拽Word文件到这里或点击选择文件';
                reviewUploadArea.style.display = 'none';
                modelSelector.style.display = 'none';
            } else if (currentFileType === 'excel') {
                fileInput.accept = '.xlsx';
                uploadText.textContent = '拖拽Excel文件到这里或点击选择文件';
                reviewUploadArea.style.display = 'none';
                modelSelector.style.display = 'none';
            } else if (currentFileType === 'review') {
                fileInput.accept = '.docx, .xlsx';
                uploadText.textContent = '或者直接选择一个Word或Excel文件';
                reviewUploadArea.style.display = 'block';
                modelSelector.style.display = 'block';
                processReviewBtn.style.display = 'block';
            }
        }

        function resetUI() {
            loading.style.display = 'none';
            error.style.display = 'none';
            success.style.display = 'none';
            preview.innerHTML = '';
            downloadWordBtn.style.display = 'none';
            downloadExcelBtn.style.display = 'none';
            processExcelBtn.style.display = 'none';
            processReviewBtn.style.display = 'none';
            modelSelector.style.display = 'none';
            reviewUploadArea.style.display = 'none';
            uploadWordBtn.style.display = 'block';
            uploadExcelBtn.style.display = 'block';
            downloadUrl = '';
            currentFileName = '';
            tempFilePath = '';
            uploadedFiles.word = null;
            uploadedFiles.excel = null;
        }

        // 拖拽事件处理
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, preventDefaults, false);
            document.body.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            uploadArea.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, unhighlight, false);
        });

        function highlight(e) {
            uploadArea.classList.add('dragover');
        }

        function unhighlight(e) {
            uploadArea.classList.remove('dragover');
        }

        uploadArea.addEventListener('drop', handleDrop, false);
        fileInput.addEventListener('change', handleFiles, false);
        downloadWordBtn.addEventListener('click', handleDownloadWord, false);
        downloadExcelBtn.addEventListener('click', handleDownloadExcel, false);
        processExcelBtn.addEventListener('click', handleProcessExcel, false);
        processReviewBtn.addEventListener('click', handleProcessReview, false);
        uploadWordBtn.addEventListener('click', handleUploadWord, false);
        uploadExcelBtn.addEventListener('click', handleUploadExcel, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            handleFiles({ target: { files: files } });
        }

        function handleFiles(e) {
            const file = e.target.files[0];
            if (!file) return;

            if (currentFileType === 'word' && !file.name.endsWith('.docx')) {
                showError('请选择.docx格式的Word文件');
                return;
            }

            if (currentFileType === 'excel' && !file.name.endsWith('.xlsx')) {
                showError('请选择.xlsx格式的Excel文件');
                return;
            }

            if (currentFileType === 'review' && !(file.name.endsWith('.docx') || file.name.endsWith('.xlsx'))) {
                showError('请选择.docx或.xlsx格式的文件');
                return;
            }

            resetUI();
            uploadFile(file);
        }

        function uploadFile(file) {
            const formData = new FormData();
            formData.append('file', file);
            currentFileName = file.name;

            loading.style.display = 'block';

            fetch('/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    throw new Error(data.error);
                }
                
                if (currentFileType === 'word') {
                    // Word处理逻辑
                    preview.innerHTML = data.content;
                    
                    // 显示下载按钮和相关信息
                    if (data.markdown && data.markdown.path) {
                        downloadUrl = data.markdown.path;
                        downloadWordBtn.style.display = 'block';
                    }
                } else if (currentFileType === 'excel') {
                    // Excel处理逻辑
                    showSuccess('Excel文件上传成功，点击生成Prompt按钮开始处理');
                    processExcelBtn.style.display = 'block';
                    currentFileName = data.filename;
                    tempFilePath = data.tempPath;
                } else if (currentFileType === 'review') {
                    // 文档审核检查处理逻辑
                    preview.innerHTML = data.content;
                }
            })
            .catch(err => {
                showError(err.message || '处理过程中发生错误');
            })
            .finally(() => {
                loading.style.display = 'none';
            });
        }

        function handleDownloadWord() {
            if (downloadUrl) {
                window.location.href = downloadUrl;
            }
        }

        function handleDownloadExcel() {
            if (downloadUrl) {
                window.location.href = downloadUrl;
            }
        }

        function handleProcessExcel() {
            if (!currentFileName) {
                showError('请先上传Excel文件');
                return;
            }
            
            loading.style.display = 'block';
            error.style.display = 'none';
            success.style.display = 'none';
            downloadExcelBtn.style.display = 'none';
            
            // 发送请求处理Excel文件
            fetch('/process-excel', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    filename: currentFileName,
                    tempPath: tempFilePath
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    throw new Error(data.error);
                }
                
                showSuccess(data.message || 'Excel文件处理成功，可下载结果文件');
                
                // 显示下载按钮和相关信息
                if (data.download_path) {
                    downloadUrl = data.download_path;
                    downloadExcelBtn.style.display = 'block';
                }
            })
            .catch(err => {
                showError(err.message || '处理Excel文件过程中发生错误');
            })
            .finally(() => {
                loading.style.display = 'none';
            });
        }

        function handleProcessReview() {
            const wordFile = document.getElementById('wordFileInput').files[0];
            const excelFile = document.getElementById('excelFileInput').files[0];
            const modelType = document.getElementById('modelType').value;
            
            if (!wordFile || !excelFile) {
                showError('请先上传Word和Excel文件');
                return;
            }
            
            // 显示加载状态
            document.getElementById('loading').style.display = 'block';
            document.getElementById('error').style.display = 'none';
            document.getElementById('success').style.display = 'none';
            
            // 创建FormData对象
            const formData = new FormData();
            formData.append('wordFile', wordFile);
            formData.append('excelFile', excelFile);
            formData.append('modelType', modelType);
            
            // 调用服务器端的审核API
            fetch('/review-document', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(data => {
                        throw new Error(data.error || '文档审核失败');
                    });
                }
                return response.json();
            })
            .then(data => {
                document.getElementById('loading').style.display = 'none';
                if (data.success) {
                    showSuccess(data.message || '文档审核完成');
                    // 存储下载路径
                    sessionStorage.setItem('excelDownloadPath', data.download_path);
                    document.getElementById('download-excel-btn').style.display = 'inline-block';
                } else {
                    showError(data.error || '文档审核失败');
                }
            })
            .catch(error => {
                document.getElementById('loading').style.display = 'none';
                showError(error.message);
            });
        }

        function handleUploadWord() {
            const fileInput = document.createElement('input');
            fileInput.type = 'file';
            fileInput.accept = '.docx';
            fileInput.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (!file) return;
                
                uploadedFiles.word = file;
                document.getElementById('wordFileName').textContent = file.name;
                
                // 如果两个文件都已上传，启用处理按钮
                if (uploadedFiles.word && uploadedFiles.excel) {
                    processReviewBtn.style.display = 'block';
                }
            });
            fileInput.click();
        }

        function handleUploadExcel() {
            const fileInput = document.createElement('input');
            fileInput.type = 'file';
            fileInput.accept = '.xlsx';
            fileInput.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (!file) return;
                
                uploadedFiles.excel = file;
                document.getElementById('excelFileName').textContent = file.name;
                
                // 如果两个文件都已上传，启用处理按钮
                if (uploadedFiles.word && uploadedFiles.excel) {
                    processReviewBtn.style.display = 'block';
                }
            });
            fileInput.click();
        }

        function showError(message) {
            error.textContent = message;
            error.style.display = 'block';
            loading.style.display = 'none';
        }

        function showSuccess(message) {
            success.textContent = message;
            success.style.display = 'block';
        }
    </script>
</body>
</html>
